package com.speedy.course.widget

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.widget.LinearLayout
import androidx.annotation.AttrRes
import androidx.recyclerview.widget.RecyclerView
import com.speedy.course.R
import com.speedy.course.databinding.RemandFrameLayoutBinding
import com.speedy.course.ext.gone
import com.speedy.course.ext.visible

/**
 * 带空状态提示 Layout
 * @author stone
 */
class RemindFrameLayout  @JvmOverloads constructor(
    context: Context, attrs:
    AttributeSet? = null,
    @AttrRes defStyleAttr: Int = 0
) : LinearLayout(context, attrs) {

    private val binding :RemandFrameLayoutBinding by lazy {
        RemandFrameLayoutBinding.inflate(LayoutInflater.from(context), this, true)
    }


    init {

        binding.apply {

            val ta =context.theme.obtainStyledAttributes(
                    attrs,
                    R.styleable.RemindFrameLayout,
                    defStyleAttr,
                    0
                )

            val text = ta.getString(R.styleable.RemindFrameLayout_text)?:"无数据"
            val remindIcon = ta.getResourceId(R.styleable.RemindFrameLayout_icon, R.drawable.empty_0)

            tvInfo.text = text
            ivImage.setImageResource(remindIcon)

        }

    }


    fun showContentView(){
        binding.apply {
            emptyLayout.gone()
            val count = childCount -1
            for (index in 0..count){
                val view = getChildAt(index)
                if (view === emptyLayout) {
                    view.visibility = GONE
                } else {
                    view.visibility = VISIBLE
                }
            }
        }
    }



    fun showRemindView(){
        binding.apply {
            emptyLayout.visible()
            val count = childCount-1
            for (index in 0..count){
                val view = getChildAt(index)
                if (view === emptyLayout) {
                    view.visibility = VISIBLE
                } else {
                    view.visibility = GONE
                }
            }
        }
    }


    /**
     * 根据 Adapter data 自动显示空数据提示
     */
    fun registerAdapterDataObserver(adapter: RecyclerView.Adapter<*>) {
        adapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
            override fun onChanged() {
                Log.i("sss", "onChanged: ${adapter.itemCount}")
                if (adapter.itemCount > 0) {
                    showContentView()
                } else {
                    showRemindView()
                }
            }
        })
    }


    fun setOnClickListener(action:()->Unit){
        binding.ivImage.setOnClickListener {
            action()
        }
    }




}